//
//  HomeViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-4.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "HomeViewController.h"
#import "ShopListViewController.h"
#import "DeliveryViewController.h"
#import "ActivityListViewController.h"
#import "GourmetListViewController.h"
#import "CouponListViewController.h"
#import "SeatViewController.h"
#import "SearchShopViewController.h"
#import "CitysViewController.h"
#import "MyPageControl.h"
#import "MyTapGestureRecognizer.h"
#import "ShopHomeViewController.h"
#import "DbManager.h"
#import "SVProgressHUD.h"
#import <ShareSDK/ShareSDK.h>

@implementation HomeViewController

- (id)init
{
    self = [super initWithNibClass:[HomeViewController class]];
    if (self) {
        _dataSource = [[HomeDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
        [_dataSource fetchCurrentCity];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [_cityBtn setTitleForNormal:[AppSetting cityName]];
    [_dataSource fetchActivitys];
    
    if (_isToUCenter) {
        _isToUCenter = NO;
        [[AppDelegate sharedInstance].tabBarController selectedTabAtIndex:3];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)setupUI
{
    [self createNavigation:@"首页"];
    [self setStatusBarStyle:UIStatusBarStyleDefault];
    [_searchTF leftMargin:10];
    
    NSInteger pagesCount = 0;
    _pageControl = [[MyPageControl alloc] initWithFrame:CGRectMake(0, _activityView.bottom_5, ScreenWidth, 10)];
    _pageControl.userInteractionEnabled = NO;
    _pageControl.backgroundColor = [UIColor clearColor];
    _pageControl.numberOfPages = pagesCount;
    [self.view addSubview:_pageControl];
    
    [self.view addTarget:self action:@selector(tapGestureAction:)];
    [self reLayoutSubviews];
    
    _titleLabel.textColor = [UIColor colorWithHexString:@"#F13A60"];
    [_couponBtn setTitleColorNormal:[UIColor colorWithHexString:@"#666666"]];
    [_gourmetBtn setTitleColorNormal:[UIColor colorWithHexString:@"#666666"]];
    [_deliveryBtn setTitleColorNormal:[UIColor colorWithHexString:@"#666666"]];
    [_activityBtn setTitleColorNormal:[UIColor colorWithHexString:@"#666666"]];
}

- (void)setPageImages
{
    for (UIView *subview in _activityScroll.subviews) {
        [subview removeFromSuperview];
    }
    
    CGRect frame = CGRectMake(0, 0, _activityScroll.width, _activityScroll.height);
    
    NSInteger count = 0;
    NSInteger pagesCount = [_dataSource.activityList count];
    for (NSDictionary *dic in _dataSource.activityList) {
        UIView *view = [[UIView alloc] initWithFrame:frame];
        view.left = count * view.width;
        view.backgroundColor = [UIColor clearColor];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 20)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = [dic objectForKey:@"name"];
        titleLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        [view addSubview:titleLabel];
        
        UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.bottom_5, frame.size.width, 20)];
        addressLabel.backgroundColor = [UIColor clearColor];
        addressLabel.font = [UIFont systemFontOfSize:15.0f];
        addressLabel.textAlignment = NSTextAlignmentCenter;
        addressLabel.text = [dic objectForKey:@"xianqu"];
        addressLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        [view addSubview:addressLabel];
        
        MyTapGestureRecognizer *singleTap = [[MyTapGestureRecognizer alloc]initWithTarget:self action:@selector(activityAction:)];
        [singleTap setTag:count];
        [view addGestureRecognizer:singleTap];
        [view autoHeight];
        
        [_activityScroll addSubview:view];
        count++;
    }
    _activityScroll.contentWidth = _activityScroll.width*pagesCount;
    _pageControl.currentPage = 0;
    _pageControl.numberOfPages = pagesCount;
    
    [self initTimer];
    [self reLayoutSubviews];
}

- (void)reLayoutSubviews
{
    _activityScroll.height = 44;
    [_activityView autoHeight];

    float margin = ScreenHeight > 480 ? 15 : 10;
    [UIView autoLayoutVertical:@[_headView, _findView,_buttonsView,_activityView,_pageControl] withMargin:margin];
}

- (void)activityAction:(id)sender
{    
    NSDictionary *dic = [_dataSource.activityList objectAtIndex:[sender tag]];
    NSString *shopId = [dic objectForKey:@"id"];
    
    ShopHomeViewController *shopHomeVC = [[ShopHomeViewController alloc] initWithId:shopId];
    [AppDelegate changeToShopTabBar:shopHomeVC];
    [self.navigationController pushViewController:shopHomeVC animated:YES];
}

- (void)initTimer
{
    //时间间隔
    NSTimeInterval timeInterval = 5.0;
    
    if (self.pageTimer) {
        [self.pageTimer invalidate];
    }
    
    //定时器
    self.pageTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval
                                                      target:self
                                                    selector:@selector(autoPage:)
                                                    userInfo:nil
                                                     repeats:YES];
}

int direction = 0;
- (void)autoPage:(NSTimer *)theTimer
{
    int index = _pageControl.currentPage;
    int max = [_dataSource.activityList count]-1;
    if (direction == 0 && index < max) {
        index++;
    }else if(direction == 0 && index == max){
        index--;
        direction = 1;
    }else if(direction == 1 && index > 0){
        index--;
    }else if(direction == 1 && index == 0){
        index++;
        direction = 0;
    }
    [_pageControl setCurrentPage:index];
    [self pageTurn];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.frame;
    [_pageControl setCurrentPage:offset.x/bounds.size.width];
}

- (void)pageTurn
{
    //令UIScrollView做出相应的滑动显示
    CGSize size = _activityScroll.frame.size;
    int page = _pageControl.currentPage;
    [_activityScroll setContentOffset:CGPointMake(page * size.width, 0) animated:YES];
}

#pragma 点击手势回调函数
- (void)tapGestureAction:(id)sender
{
    [_searchTF resignFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [self search];
        return NO;
    }
    
    return YES;
}

- (IBAction)buttonPress:(id)sender
{
    UIButton *button = (UIButton*)sender;
    switch (button.tag) {
        case 0:
            //兰州
            break;
        case 1: {
            [self search];
            break;
        }
        case 2: {
            [self pushController:[ShopListViewController class]];
            break;
        }
        case 3: {
            [self pushController:[CouponListViewController class]];
            break;
        }
        case 4: {
            [self pushController:[GourmetListViewController class]];
            break;
        }
        case 5: {
            [self pushController:[DeliveryViewController class]];
            break;
        }
        case 6: {
            [self pushController:[ActivityListViewController class]];
            break;
        }
    }
}

- (void)pushController:(Class)class
{
    id viewController = [[class alloc] init];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)search
{
    NSString *keyword = _searchTF.text;
    if ([keyword isEqualToString:@""]) {
        [AppDelegate showMessage:@"请输入关键字进行搜索！"];
        return;
    }
    
    [_searchTF resignFirstResponder];
    SearchShopViewController *searchVC = [[SearchShopViewController alloc] initWithKeyword:keyword];
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (IBAction)changeCityAction:(id)sender
{
    CitysViewController *cityVC = [[CitysViewController alloc] init];
    cityVC.parentViewController = self;
    [self pushViewController:cityVC];
}

- (void)selectedDidCity:(NSDictionary *)city
{
    NSString *cityName = [city objectForKey:@"name"];
    [AppSetting setObject:cityName forKey:@"cityName"];
    
    [_cityBtn setTitleForNormal:[AppSetting cityName]];
}

- (void)switchCity
{
    [_cityBtn setTitleForNormal:[AppSetting cityName]];
    [[BaseDataManager sharedInstance] startDownLoad2];
    [_dataSource fetchActivitys];
}

@end

//==========================================================================================
#pragma ===================数据源类实现=======================================================
//==========================================================================================

#define CAIXI_TAG 1001
#define XIANQU_TAG 1002
#define ORDER_TAG  1003
#define JULI_TAG   1004
#define ACTIVITY_TAG 1005
#define DATA_VERSION_TAG 1006
#define FETCH_CITY_TAG 1007

@implementation HomeDataSource

int count = 0;
int responseCount = 0;

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _activityList = [[NSMutableArray alloc] initWithCapacity:3];
    }
    return self;
}

- (void)fetchCurrentCity
{
    NSString *url = [NSString stringWithFormat:API_FETCH_CITY, [AppSetting longitude],[AppSetting latitude]];
    [self get:url tag:FETCH_CITY_TAG];
}

- (void)fetchActivitys
{
    NSString *url = [NSString stringWithFormat:API_TODAY,[AppSetting cityId]];
    [self get:url tag:ACTIVITY_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    CLog(@"%@", request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    if (request.tag == ACTIVITY_TAG) {
        self.activityList = [json objectForKey:@"dinner"];
        [_viewController setPageImages];
    }
    
    if(request.tag == FETCH_CITY_TAG) {
        NSDictionary *city = [json objectForKey:@"city"];
        _cityId = [city objectForKey:@"id"];
        _cityName = [city objectForKey:@"name"];
        
        if(![[AppSetting cityId] isEqualToString:_cityId]) {
            NSString *text = [NSString stringWithFormat:@"系统定位您现在在%@, 是否要切换到%@?", _cityName,_cityName];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:text delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"切换", nil];
            [alert show];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [AppSetting setCityId:_cityId];
        [AppSetting setCityName:_cityName];
        
        [_viewController switchCity];
    }
}

@end

//13893220800
//658883


